package com.example.cadmin.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.cadmin.entity.MyRole;
import com.example.cadmin.entity.MyRoleMenu;
import com.example.cadmin.entityVo.MenuALLVo;
import com.example.cadmin.entityVo.RoleDto;
import com.example.cadmin.mapper.MyRoleMapper;
import com.example.cadmin.mapper.MyRoleMenuMapper;
import com.example.cadmin.utils.ResponseModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zzsoft
 * @since 2023-01-07
 */
@Service
public class MyRoleService extends ServiceImpl<MyRoleMapper, MyRole> {
    @Resource
    private MyRoleMapper myRoleMapper;
    @Resource
    private MyRoleMenuMapper myRoleMenuMapper;

    /**
     * 获取角色列表
     */
    public Map<String, Object> roleList() {
        List<MyRole> roleList = myRoleMapper.selectList(null);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "数据请求成功");
        map.put("count", roleList.size());
        map.put("data", roleList);
        return map;
    }

    /*
    获取所有的菜单,绘制菜单树
     */
    public List<MenuALLVo> buildMenuAll() {
        return myRoleMapper.buildAll();
    }

    /*
    判断角色名数据库是否已存在
     */
    public Boolean checkRole(String roleName) {
        MyRole myRole = myRoleMapper.selectOne(new QueryWrapper<MyRole>().eq("role_name", roleName));
        return myRole != null;
    }

    /*
    插入角色信息
     */
    public ResponseModel save(RoleDto roleDto) {
        try {
            // 1.先验证用户名是否已存在
            Boolean bool = checkRole(roleDto.getRoleName());
            if (bool) {
                return ResponseModel.fail("角色名已存在,无法创建");
            }
            // 2、先保存角色"
            roleDto.setCreateTime(DateUtil.now());
            roleDto.setUpdateTime(DateUtil.now());
            myRoleMapper.save(roleDto);
            // 3、保存角色对应的所有权限
            List<Integer> menuIds = roleDto.getMenuIds();
            if (menuIds.size() > 0) {
                myRoleMenuMapper.save(roleDto.getRoleId(), menuIds);
            }
            return ResponseModel.success("添加成功");
        } catch (Exception e) {
            return ResponseModel.fail("添加失败");
        }
    }

    /*
    获取角色的信息
     */
    public Map<String, Object> getColeInfo(int roleId) {
//        return myRoleMapper.selectMaps(new QueryWrapper<MyRole>().eq("role_id",roleId));
        return myRoleMapper.getRole(roleId);
    }

    /*
    获取所有已授权菜单树
     */
    public List<MenuALLVo> buildMenuAllByRoleId(int roleId) {
        //获取所有的菜单栏
        List<MenuALLVo> menuALLVoList = myRoleMapper.buildAll();
        // 获取所有的
        List<MyRoleMenu> list = myRoleMenuMapper.selectList(new QueryWrapper<MyRoleMenu>().eq("role_id", roleId).select("menu_id"));
        List<Integer> menuIds = new ArrayList<>();
        for (MyRoleMenu myRoleMenu : list) {
            menuIds.add(myRoleMenu.getMenuId());
        }
        for (MenuALLVo menuALLVo : menuALLVoList) {
            if (menuIds.contains(menuALLVo.getId())) {
                menuALLVo.setCheckArr("1");
            }
        }
        return menuALLVoList;
    }

    /*
    更新用户信息
     */
    public ResponseModel update(RoleDto roleDto) {
        try {
            // 更新权限前先删除前面所有的权限
            myRoleMenuMapper.delete(new QueryWrapper<MyRoleMenu>().eq("role_id", roleDto.getRoleId()));
            // 重新写入权限
            if (roleDto.getMenuIds().size() > 0) {
                myRoleMenuMapper.save(roleDto.getRoleId(), roleDto.getMenuIds());
            }
            //修改用户信息
            MyRole myRole = new MyRole();
            myRole.setRoleId(roleDto.getRoleId());
            myRole.setDescription(roleDto.getDescription());
            myRole.setUpdateTime(DateUtil.now());
            myRoleMapper.updateById(myRole);
            return ResponseModel.success("角色修改成功");
        } catch (Exception e) {
            return ResponseModel.fail("角色修改失败");
        }
    }

    /*
    删除用户角色
     */
    public ResponseModel remove(String roleId) {
        try {
            String[] strings = roleId.split(",");
            List<String> idList = CollUtil.newArrayList(strings);
            //先删除角色已授权菜单树数据
            for (String id : idList) {
                // 由于一个id对应多条数据，无法使用内置方法deleteBatchIds
                myRoleMenuMapper.delete(new QueryWrapper<MyRoleMenu>().eq("role_id", id));
            }
            // 删除角色表信息
            myRoleMapper.deleteBatchIds(idList);
            return ResponseModel.success("删除成功");
        } catch (Exception e) {
            return ResponseModel.fail("删除失败");
        }
    }

    /*
    获取所有角色列表
     */
    public ResponseModel all() {
        List<Map<String, Object>> myRoleList = myRoleMapper.selectMaps(null);
        return ResponseModel.success(myRoleList);
    }

    /**
     * 通过id获得角色信息
     *
     * @param
     * @return
     */
    public MyRole getRoleById(Integer id) {
        return myRoleMapper.getRoleById(id);
    }
}
